/* USER CODE BEGIN Header */
/**
 ******************************************************************************
 * @file           : main.c
 * @brief          : Main program body
 ******************************************************************************
 * @attention
 *
 * <h2><center>&copy; Copyright (c) 2021 STMicroelectronics.
 * All rights reserved.</center></h2>
 *
 * This software component is licensed by ST under BSD 3-Clause license,
 * the "License"; You may not use this file except in compliance with the
 * License. You may obtain a copy of the License at:
 *                        opensource.org/licenses/BSD-3-Clause
 *
 ******************************************************************************
 */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "adc.h"
#include "tim.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "fsm.h"
#include <stdio.h>
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
//数据接收结构
Uart_Struct_t Uart_Struct;
FSM_Struct_t FSM_Struct;
/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */
uint8_t value[1] = {0};

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
static void system_config_before_stop(void)
{
	HAL_UART_DeInit(&huart1);
	HAL_ADC_DeInit(&hadc);
	/* Disable GPIOs clock */
	__HAL_RCC_GPIOA_CLK_DISABLE();
	__HAL_RCC_GPIOB_CLK_DISABLE();
	__HAL_RCC_GPIOC_CLK_DISABLE();
}

static void stop_exit_config(void)
{
	GPIO_InitTypeDef GPIO_Initure = {0};
	__HAL_RCC_GPIOA_CLK_ENABLE();

	GPIO_Initure.Pin = GPIO_PIN_10;
	GPIO_Initure.Mode = GPIO_MODE_IT_FALLING;
	GPIO_Initure.Pull = GPIO_PULLUP;
	HAL_GPIO_Init(GPIOA, &GPIO_Initure);
	HAL_NVIC_SetPriority(EXTI4_15_IRQn, 2, 0);
	HAL_NVIC_EnableIRQ(EXTI4_15_IRQn);

	GPIO_Initure.Pin = GPIO_PIN_9;
	GPIO_Initure.Mode = GPIO_MODE_ANALOG;
	GPIO_Initure.Pull = GPIO_NOPULL;
	HAL_GPIO_Init(GPIOA, &GPIO_Initure);
}

// UART.c
/**
 * @brief 串口中断回调函数
 * @param 调用回调函数
 * @note
 * @retval None
 */
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
	if (huart->Instance == USART1)
	{
		__HAL_TIM_SET_COUNTER(&htim3, 0);
		if (0 == Uart_Struct.Rx_Count) //如果是第1个字符，则开启定时器
		{
			__HAL_TIM_CLEAR_FLAG(&htim3, TIM_FLAG_UPDATE);
			HAL_TIM_Base_Start_IT(&htim3);
		}
		Uart_Struct.Rx_Buf[Uart_Struct.Rx_Count] = Uart_Struct.Rx_temp[0];
		Uart_Struct.Rx_Count++;
		HAL_UART_Receive_IT(&huart1, (uint8_t *)Uart_Struct.Rx_temp, REC_LENGTH);
	}
}

/**
 * @brief 定时器回调函数，定时器中断服务函数调
 * @param 定时器中断序
 * @retval None
 */
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
	if (htim == (&htim3))
	{
		Uart_Struct.Rx_flg = 1;
		HAL_TIM_Base_Stop_IT(&htim3); //关闭定时器
	}
	else if (htim == (&htim6))
	{
		AnalogUart_IO_TIM_Handler();
	}
	else if (htim == (&htim14))
	{
		AnalogUart_TimeOut_TIM_Handler();
	}
}

uint16_t ADC_Value = 0;
uint16_t Get_ADC_Value()
{
	// ADC1
	HAL_ADC_Start(&hadc);
	//等待ADC转换完成，超时为100ms
	HAL_ADC_PollForConversion(&hadc, 100);
	//判断ADC是否转换成功
	if (HAL_IS_BIT_SET(HAL_ADC_GetState(&hadc), HAL_ADC_STATE_REG_EOC))
	{
		//读取
		return HAL_ADC_GetValue(&hadc);
	}
	return 0x5AA5;
}

EventID Uart_Report(void)
{
	EventID event;
	// 串口触发
	if (Uart_Struct.Rx_flg)
	{
		// Uart_Handler
		HAL_UART_Transmit(&huart1, Uart_Struct.Rx_Buf, Uart_Struct.Rx_Count, 0x10);

		if (strcmp((const char *)Uart_Struct.Rx_Buf, "Red\r\n") == 0)
			event = event_3;
		if (strcmp((const char *)Uart_Struct.Rx_Buf, "OPM\r\n") == 0)
			event = event_4;
		if (strcmp((const char *)Uart_Struct.Rx_Buf, "Sleep\r\n") == 0)
			event = event_5;
		if (strcmp((const char *)Uart_Struct.Rx_Buf, "Cal\r\n") == 0)
			event = event_6;

		for (int i = 0; i < Uart_Struct.Rx_Count; i++)
			Uart_Struct.Rx_Buf[i] = 0;
		Uart_Struct.Rx_Count = 0;
		Uart_Struct.Rx_flg = 0;
		return event;
	}
	// 其他方式触发 同时 事件 4 只会通过串口进行通知
	else if (FSM_Struct.FSM_EventType != 0 && FSM_Struct.FSM_EventType != event_4)
	{
		return FSM_Struct.FSM_EventType;
	}
	else
		return 0;
}

StateMachine stateMachine;
void FSM_Init(void)
{
	stateMachine.state = state_1;
	stateMachine.transNum = 13;
	stateMachine.transform = stateTran;
	runStateMachine(&stateMachine, event_1); // 自动休眠

	// runStateMachine(&stateMachine, event_2); // 唤醒
}

char Sleep(const EventID *ID)
{
	printf("State Sleep\r\n");
	HAL_SuspendTick();

	system_config_before_stop();
	stop_exit_config();
	// 进入睡眠模式
	// HAL_PWR_EnterSLEEPMode(PWR_MAINREGULATOR_ON,PWR_SLEEPENTRY_WFI);
	// 进入停止模式
	// HAL_PWR_EnterSTOPMode(PWR_MAINREGULATOR_ON,PWR_STOPENTRY_WFI);   //电压调节器正�??????
	HAL_PWR_EnterSTOPMode(PWR_LOWPOWERREGULATOR_ON, PWR_STOPENTRY_WFI); //电压调节器低功率
	return 0;
}

char Ready_Ack(const EventID *ID)
{
	/* 恢复系统时钟中断 */
	HAL_ResumeTick();
	MX_GPIO_Init();
	MX_USART1_UART_Init();
	MX_ADC_Init();
	HAL_UART_Receive_IT(&huart1, (uint8_t *)Uart_Struct.Rx_temp, REC_LENGTH);
	printf("State Ready_Ack\r\n");
	return 0;
}

char Red_Light(const EventID *ID)
{
	printf("State Red_Light\r\n");
	return 0;
}

char OPM_Read(const EventID *ID)
{
	printf("State OPM_Read\r\n");
	return 0;
}

char OPM_Red_On(const EventID *ID)
{
	printf("State OPM_Red_On\r\n");
	return 0;
}

char Cal(const EventID *ID)
{
	printf("State Cal\r\n");
	return 0;
}
/* USER CODE END 0 */

/**
 * @brief  The application entry point.
 * @retval int
 */
int main(void)
{
	/* USER CODE BEGIN 1 */
	/* USER CODE END 1 */

	/* MCU Configuration--------------------------------------------------------*/

	/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
	HAL_Init();

	/* USER CODE BEGIN Init */

	/* USER CODE END Init */

	/* Configure the system clock */
	SystemClock_Config();

	/* USER CODE BEGIN SysInit */

	/* USER CODE END SysInit */

	/* Initialize all configured peripherals */
	MX_GPIO_Init();
	MX_USART1_UART_Init();
	MX_ADC_Init();
	MX_TIM3_Init();
	MX_TIM6_Init();
	MX_TIM14_Init();
	/* USER CODE BEGIN 2 */
	// FSM Init 初始化状态机
	// FSM_Init();
	// Initialize structure
	AnalogUart_Init_Struct();
	// 清除TIM3 TIM6的标志位
	__HAL_TIM_CLEAR_FLAG(&htim3, TIM_FLAG_UPDATE);
	__HAL_TIM_CLEAR_FLAG(&htim6, TIM_FLAG_UPDATE);
	__HAL_TIM_CLEAR_FLAG(&htim14, TIM_FLAG_UPDATE);
	// 串口中断 使能
	HAL_UART_Receive_IT(&huart1, (uint8_t *)Uart_Struct.Rx_temp, REC_LENGTH);
	/* USER CODE END 2 */

	/* Infinite loop */
	/* USER CODE BEGIN WHILE */
	while (1)
	{
		/* USER CODE END WHILE */

		/* USER CODE BEGIN 3 */
		// FSM_Struct.FSM_EventType = Uart_Report();
		// if (FSM_Struct.FSM_EventType != 0)
		//   // 自动休眠
		//   runStateMachine(&stateMachine, FSM_Struct.FSM_EventType);

		if (AnalogUart_Data_Struct.USART_Rx_Done == 1)
		{
			USART_Send(AnalogUart_Data_Struct.USART_buf, AnalogUart_Data_Struct.USART_len);
			memset(AnalogUart_Data_Struct.USART_buf, 0, sizeof(AnalogUart_Data_Struct.USART_buf));
			AnalogUart_Data_Struct.USART_len = 0;
			AnalogUart_Data_Struct.USART_Rx_Done = 0;
		}
	}
	/* USER CODE END 3 */
}

/**
 * @brief System Clock Configuration
 * @retval None
 */
void SystemClock_Config(void)
{
	RCC_OscInitTypeDef RCC_OscInitStruct = {0};
	RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
	RCC_PeriphCLKInitTypeDef PeriphClkInit = {0};

	/** Initializes the RCC Oscillators according to the specified parameters
	 * in the RCC_OscInitTypeDef structure.
	 */
	RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI | RCC_OSCILLATORTYPE_HSI14;
	RCC_OscInitStruct.HSIState = RCC_HSI_ON;
	RCC_OscInitStruct.HSI14State = RCC_HSI14_ON;
	RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
	RCC_OscInitStruct.HSI14CalibrationValue = 16;
	RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
	if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
	{
		Error_Handler();
	}
	/** Initializes the CPU, AHB and APB buses clocks
	 */
	RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_PCLK1;
	RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_HSI;
	RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
	RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;

	if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_0) != HAL_OK)
	{
		Error_Handler();
	}
	PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_USART1;
	PeriphClkInit.Usart1ClockSelection = RCC_USART1CLKSOURCE_PCLK1;
	if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
	{
		Error_Handler();
	}
}

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

/**
 * @brief  This function is executed in case of error occurrence.
 * @retval None
 */
void Error_Handler(void)
{
	/* USER CODE BEGIN Error_Handler_Debug */
	/* User can add his own implementation to report the HAL error return state */
	__disable_irq();
	while (1)
	{
	}
	/* USER CODE END Error_Handler_Debug */
}

#ifdef USE_FULL_ASSERT
/**
 * @brief  Reports the name of the source file and the source line number
 *         where the assert_param error has occurred.
 * @param  file: pointer to the source file name
 * @param  line: assert_param error line source number
 * @retval None
 */
void assert_failed(uint8_t *file, uint32_t line)
{
	/* USER CODE BEGIN 6 */
	/* User can add his own implementation to report the file name and line number,
	   ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
	/* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
